﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace Dell.ZhiJianQian.WeiXin.UI
{
    public class Oauth
    {
        public Oauth() { }
        #region 微信OAuth2.0网页授权流程

        //1 第一步：用户同意授权，获取code
        //    https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
        //    如果用户同意授权，页面将跳转至 redirect_uri/?code=CODE&state=STATE。若用户禁止授权，则重定向后不会带上code参数，仅会带上state参数redirect_uri?state=STATE 


        //2 第二步：通过code换取网页授权access_token
        //    https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        //    返回说明
        //    正确时返回的JSON数据包如下：
        //    {
        //       "access_token":"ACCESS_TOKEN",
        //       "expires_in":7200,
        //       "refresh_token":"REFRESH_TOKEN",
        //       "openid":"OPENID",
        //       "scope":"SCOPE"
        //    }

        //    错误时微信会返回JSON数据包如下（示例为Code无效错误）:
        //    {"errcode":40029,"errmsg":"invalid code"}


        //3 第三步：刷新access_token（如果需要）
        //    https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN

        //    返回说明
        //    正确时返回的JSON数据包如下：

        //    {
        //       "access_token":"ACCESS_TOKEN",
        //       "expires_in":7200,
        //       "refresh_token":"REFRESH_TOKEN",
        //       "openid":"OPENID",
        //       "scope":"SCOPE"
        //    }
        //    错误时微信会返回JSON数据包如下（示例为Code无效错误）:
        //    {"errcode":40029,"errmsg":"invalid code"}


        //4 第四步：拉取用户信息(需scope为 snsapi_userinfo)
        //    请求方法
        //    http：GET（请使用https协议）
        //    https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

        //    返回说明
        //    正确时返回的JSON数据包如下：
        //    {
        //    "openid":" OPENID",
        //    " nickname": NICKNAME,
        //    "sex":"1",
        //    "province":"PROVINCE"
        //    "city":"CITY",
        //    "country":"COUNTRY",
        //    "headimgurl":    "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46", 
        //    "privilege":[
        //    "PRIVILEGE1"
        //    "PRIVILEGE2"
        //    ]
        //    }

        //    错误时微信会返回JSON数据包如下（示例为openid无效）:
        //    {"errcode":40003,"errmsg":" invalid openid "}


        #endregion

        private string strAppID = ConfigurationManager.AppSettings["appid"];
        private string strAppSercet = ConfigurationManager.AppSettings["appsecret"];
        private string strRedirect_uri = ConfigurationManager.AppSettings["redirect_uri"];

        /// <summary>
        /// getcode 
        /// </summary>
        /// <param name="strInput">("snsapi_userinfo" or "snsapi_base")</param>
        /// <returns>code</returns>
        public string GetCode(string strInput)
        {
            string strUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state={3}#wechat_redirect";
            return string.Format(strUrl, strAppID, HttpUtility.UrlEncode(strRedirect_uri), strInput, strInput.Replace("_", ""));
        }
        /// <summary>
        /// 获取Access_Token
        /// </summary>
        /// <param name="strCode">服务端返回的code</param>
        /// <returns>Access_Token</returns>
        public string GetAccessToken(string strCode)
        {
            string strUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code";
            string strResult = string.Empty;
            if (string.IsNullOrEmpty(strCode))
            {
                strResult = "code is null";
            }
            else
            {
                strUrl = string.Format(strUrl, strAppID, strAppSercet, strCode);

                WebRequest wReq = WebRequest.Create(strUrl);
                WebResponse wResp = wReq.GetResponse();
                Stream respStream = wResp.GetResponseStream();
                using (StreamReader reader = new StreamReader(respStream, Encoding.Default))
                {
                    strResult = reader.ReadToEnd();
                }

                //HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create(strUrl);
                //HttpWebResponse hwrs = (HttpWebResponse)hwr.GetResponse();
                //Stream stream = hwrs.GetResponseStream();
                //StreamReader strReader = new StreamReader(stream, Encoding.Default);
                //StringBuilder sb = new StringBuilder();
                //while (-1 != strReader.Peek())
                //{
                //    sb.Append(strReader.ReadLine());
                //}
                //hwrs.Close();
                //strResult = sb.ToString();
            }
            return strResult;
        }
        /// <summary>
        /// 刷新AccessToken
        /// </summary>
        /// <param name="strRefreshToken"></param>
        /// <returns></returns>
        public string RefreshToken(string strRefreshToken)
        {
            string strUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={0}&grant_type=refresh_token&refresh_token={1}";
            string strResult = string.Empty;
            if (string.IsNullOrEmpty(strRefreshToken))
            {
                strResult = "refreshtoken is null";
            }
            else
            {
                strUrl = string.Format(strUrl, strAppID, strRefreshToken);

                WebRequest wReq = WebRequest.Create(strUrl);
                WebResponse wResp = wReq.GetResponse();
                Stream respStream = wResp.GetResponseStream();
                using (StreamReader reader = new StreamReader(respStream, Encoding.Default))
                {
                    strResult = reader.ReadToEnd();
                }

            }
            return strResult;
        }
        /// <summary>
        /// 拉取用户信息
        /// </summary>
        /// <param name="strOpenID">用户唯一标示</param>
        /// <param name="strAccessToken">AccessToken</param>
        /// <returns>用户信息(用户标示,昵称,性别,地理位置,头像地址等)</returns>
        public string GetUserInfo(string strOpenID, string strAccessToken)
        {
            string strUrl = "https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN";
            string strResult = string.Empty;
            if (string.IsNullOrEmpty(strOpenID) || string.IsNullOrEmpty(strAccessToken))
            {
                strResult = "openid or accesstoken is null";
            }
            else
            {
                strUrl = string.Format(strUrl, strAccessToken, strAppID);

                WebRequest wReq = WebRequest.Create(strUrl);
                WebResponse wResp = wReq.GetResponse();
                Stream respStream = wResp.GetResponseStream();
                using (StreamReader reader = new StreamReader(respStream, Encoding.UTF8))
                {
                    strResult = reader.ReadToEnd();
                }

            }
            return strResult;
        }

    }
}